package com.leon.alishop.spider.worker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leon.alishop.core.config.ProviderConstant;
import com.leon.alishop.core.enumeration.GoodsStatusEnum;
import com.leon.alishop.core.util.AliShopStringUtils;
import com.leon.alishop.dao.GoodsInfoDao;
import com.leon.alishop.model.GoodsInfo;
import com.leon.alishop.model.ProviderInfo;
import com.leon.alishop.spider.config.SpiderProperties;
import com.leon.alishop.spider.model.TaobaoGoodsInfo;
import com.leon.alishop.spider.service.TaobaoGoodsService;
import com.leon.alishop.spider.spider.CrawlAlibabaSpider;
import com.leon.alishop.spider.spider.CrawlTaobaoSpider;

/**
 * 查询阿里巴巴的商品状态
 * 
 * @author Leon
 * 
 */
public class AlibabaShopGoodsStatusCrawlThread implements Runnable {
	private static Logger log = LoggerFactory
			.getLogger(AlibabaShopGoodsStatusCrawlThread.class);
	private static volatile boolean isRun;

	private Thread currentThread;

	private boolean fromAlibabaWeb = false;
	
	@Override
	public void run() {
		if(isRun)
			return;
		isRun = true;
		currentThread = Thread.currentThread();
		String aliShopHomeUrl = SpiderProperties.getAlibabaStoreHomeUrl();
		long timemill;
		long totalTimemill = System.currentTimeMillis();
		List<GoodsInfo> alishopGoodsList =null;
		List<GoodsInfo> dataBaseGoods = null;
		List<String> itemUrls = new ArrayList<String>();
		Map<Long,Long> aliGoodsIdMap = new HashMap<Long, Long>();
		if(fromAlibabaWeb){
			//获取阿里所有的商品
			alishopGoodsList = crawlAlibabaSpider.crawlAllItemList(aliShopHomeUrl);
			List<Long> goodsIds = new ArrayList<Long>();
			for (GoodsInfo gi : alishopGoodsList) {
				if(gi.getId()==null){
					log.error("商品ID为空 阿里商品ID："+gi.getTaobaoGoodsId());
				}else{
					goodsIds.add(gi.getId());
					if(aliGoodsIdMap.containsKey(gi.getId())){
						log.error("出现了重复的商品货号："+gi.getId());
						isRun = false;
						return;
					}
					if(gi.getTaobaoGoodsId()!= null){
						aliGoodsIdMap.put(gi.getId(), gi.getTaobaoGoodsId());
					}
				}
			}
			if(goodsIds.size()>0){
				dataBaseGoods = goodsInfoDao.selectByIds(goodsIds.toArray(new Long[goodsIds.size()]));
			}
			
		}else{
			//直接从数据库获取
			dataBaseGoods = goodsInfoDao.selectAll(null, null,null, new Integer[]{GoodsStatusEnum.ONLINE.ordinal()}, 0, 5000);
		}
		Map<Long,ProviderInfo> goodsIdProviderIdMap = new HashMap<Long,ProviderInfo>();
		if(dataBaseGoods != null && dataBaseGoods.size()>0){
			for (GoodsInfo gi : dataBaseGoods) {
				itemUrls.add(formatTaobaoItemUrl(gi.getProviderTaobaoGoodsId()));
				goodsIdProviderIdMap.put(gi.getProviderTaobaoGoodsId(), ProviderConstant.getInstance().getProviderInfoById(gi.getProviderId()));
			}
		}
		ProviderInfo pi = new ProviderInfo();
		pi.setId(0);
		List<TaobaoGoodsInfo> taobaoGoodsList = crawlTaobaoSpider.crawlItemUrl(pi, itemUrls);
		List<TaobaoGoodsInfo> taobaoGoodsListTemp = new ArrayList<TaobaoGoodsInfo>(1);
		taobaoGoodsListTemp.add(null);
		Set<Long> taobaoGoodsIdSet = new HashSet<Long>();
		if(taobaoGoodsList != null && taobaoGoodsList.size()>0){
			for (TaobaoGoodsInfo tgi : taobaoGoodsList) {
				taobaoGoodsIdSet.add(tgi.getProviderTaobaoGoodsId());
				taobaoGoodsListTemp.set(0, tgi);
				pi = goodsIdProviderIdMap.get(tgi.getProviderTaobaoGoodsId());
				if(null != pi){
					taobaoGoodsService.insertTaobaoGoodsSku(pi,taobaoGoodsListTemp,false);
				}else{
					log.error("未找到供货商ID:"+tgi.getProviderId()+"\tgoodsid:"+tgi.getProviderTaobaoGoodsId());
				}
			}
		}
		GoodsInfo _gi;
		log.info("更新商品状态！");
		if(dataBaseGoods != null && dataBaseGoods.size()>0){
			for (GoodsInfo gi : dataBaseGoods) {
				if(!taobaoGoodsIdSet.contains(gi.getProviderTaobaoGoodsId())){
					_gi = new GoodsInfo();
					_gi.setId(gi.getId());
					_gi.setTaobaoGoodsId(gi.getTaobaoGoodsId());
					_gi.setProviderStatus(GoodsStatusEnum.OFFLINE.ordinal());
					goodsInfoDao.updateByIdSelective(_gi);
				}else{
					if(GoodsStatusEnum.ONLINE.ordinal() != gi.getStatus().intValue()
							|| gi.getTaobaoGoodsId() == null){
						_gi = new GoodsInfo();
						_gi.setId(gi.getId());
						if(aliGoodsIdMap.containsKey(gi.getId())){
							_gi.setTaobaoGoodsId(aliGoodsIdMap.get(gi.getId()));
						}
						_gi.setStatus(GoodsStatusEnum.ONLINE.ordinal());
						goodsInfoDao.updateByIdSelective(_gi);
					}
				}
			}
		}
		log.info("执行完毕，耗时："+AliShopStringUtils.sec2Time(System.currentTimeMillis()-totalTimemill));
		isRun = false;
	}
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	private String formatTaobaoItemUrl(Long id) {
		return "http://item.taobao.com/item.htm?id="+String.valueOf(id);
	}
	
	private GoodsInfoDao goodsInfoDao;
	
	private CrawlTaobaoSpider crawlTaobaoSpider;
	
	private CrawlAlibabaSpider crawlAlibabaSpider;
	
	private TaobaoGoodsService taobaoGoodsService;
	
	public void setCrawlTaobaoSpider(CrawlTaobaoSpider crawlTaobaoSpider) {
		this.crawlTaobaoSpider = crawlTaobaoSpider;
	}

	public void setTaobaoGoodsService(TaobaoGoodsService taobaoGoodsService) {
		this.taobaoGoodsService = taobaoGoodsService;
	}

	public void setFromAlibabaWeb(boolean fromAlibabaWeb) {
		this.fromAlibabaWeb = fromAlibabaWeb;
	}

	public void setGoodsInfoDao(GoodsInfoDao goodsInfoDao) {
		this.goodsInfoDao = goodsInfoDao;
	}

	public void setCrawlAlibabaSpider(CrawlAlibabaSpider crawlAlibabaSpider) {
		this.crawlAlibabaSpider = crawlAlibabaSpider;
	}
	
}
